package com.gobang.modules.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gobang.entity.User;
import com.gobang.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 登录或注册
     */
    public User loginOrRegister(String username, String password) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        
        if (user == null) {
            // 注册新用户
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setScore(1000);
            user.setWinCount(0);
            user.setLoseCount(0);
            user.setDrawCount(0);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0);
            userMapper.insert(user);
        } else {
            // 验证密码
            if (!password.equals(user.getPassword())) {
                return null;
            }
        }
        
        return user;
    }
    
    /**
     * 更新用户战绩
     */
    public void updateUserStats(Long userId, boolean isWin, boolean isDraw) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            if (isWin) {
                user.setWinCount(user.getWinCount() + 1);
                user.setScore(user.getScore() + 20);
            } else if (isDraw) {
                user.setDrawCount(user.getDrawCount() + 1);
            } else {
                user.setLoseCount(user.getLoseCount() + 1);
                user.setScore(Math.max(0, user.getScore() - 10));
            }
            user.setUpdateTime(LocalDateTime.now());
            userMapper.updateById(user);
        }
    }
    
    /**
     * 获取用户信息
     */
    public User getUserById(Long userId) {
        return userMapper.selectById(userId);
    }
}
